<template>
  <div class="chatbot-wrapper">
    <div class="title">调试预览</div>
    <div class="content" ref="conversationRef">
      <div class="chat-list">
        <div class="chat-item" :class="{client: item.source == SOURCE_VALUE.CLIENT}" v-for="item in chatList" >
          <div class="chat-toolbar" v-if="item.source == SOURCE_VALUE.CLIENT">
            <div class="tools">
              <div class="btn"><Icon type="md-copy" color="#8a95a7" size="16" @click="onCopy(item.word)" /></div>
              <div class="btn"><Icon type="md-refresh" color="#8a95a7" size="16" /></div>
              <div class="btn"><Icon type="ios-trash" color="#8a95a7" size="16" /></div>
            </div>
            <img :src="item.avatar" alt="avatar" class="avatar" v-if="item.avatar">
            <Icon v-else class="user-icon" type="md-person" size="28" />
          </div>
          <div class="chat-toolbar" v-else>
            <img :src="item.avatar || DefaultImg" alt="avatar" class="avatar">
            <div class="tools">
              <div class="btn"><Icon type="md-copy" color="#8a95a7" size="16" @click="onCopy(item.word)" /></div>
              <div class="btn"><Icon type="md-refresh" color="#8a95a7" size="16" /></div>
              <div class="btn"><Icon type="md-create" color="#8a95a7" size="16" /></div>
            </div>
          </div>
          <div class="chat-content">
            <div class="word">
              {{ item.word }}
              <div class="suggest-list">
                <div class="suggest-item" v-for="sug in item.suggest" :key="sug.id" @click="sendMessage(sug.title)">
                  {{ sug.title }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="enter">
        <Input type="textarea" v-model="sendWord" search  @keydown="handleKeyDown" size="large" :border="false" :autosize="{maxRows: 10}" placeholder="输入问题，发送 [Enter]/换行[Shift + Enter]" />   
        <Icon type="ios-mic-outline" style="padding: 0 10px;" size="35" />
        <Button type="primary" size="large" icon="md-send" :disabled="!sendWord" @click="sendMessage()"></Button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance, onBeforeUnmount, nextTick  } from 'vue';
import { userStore } from "@/store/userInfo";
import createWebSocket from '@/util/websocket'

import DefaultImg from '@/assets/imgs/default.png'

const props = defineProps({
  aiid: {
    type: String
  }
})

const { proxy } = getCurrentInstance();
const SOURCE_VALUE = {
  SERVICER: 1,
  CLIENT: 2
}

const sendWord = ref('')
const chatList = ref([])

const user = userStore();
const userInfo = user.userInfo;
const serverInfo = user.server;

const socket = createWebSocket('https://demo.zkefu.cn:443/im/ai')
const conversationRef = ref(null)

socket.on('connect', () => {
  console.log('连接成功')
  // 发送初始化消息
  socket.send('new', {
    orgi: 'ukewo',
    appid: '8da803feb3d55ee739d7400ff098256b',
    aiid: '043710be74784437bb8aa88017af5248',
    userid: '4028cac3614cd2f901614cf8be1f0324',
    user: '4028cac3614cd2f901614cf8be1f0324',
    session: 'de37fc1d0f21494aa690a1e0e854ecb1',
    debug: true,
    osname: '',
    browser: ''
  })
})

socket.on('message', data => {
  console.log('message', data)
  if (data.calltype === 'out') {
    chatList.value.push({
      ...data,
      word: data.message
    })

    nextTick(() => {
      const el = conversationRef.value
      console.log(el)
      el.scrollTop = el.scrollHeight
    })
  }
})

socket.on('agentstatus', data => {
  console.log('agentstatus', data)
})

socket.on('status', data => {
  console.log('status', data)
})

const sendMessage = (val) => {
  const searchText = val || sendWord.value
  if (!searchText) return

  chatList.value.push({
    word: searchText,
    source: SOURCE_VALUE.CLIENT
  })

  socket.send({
    appid: '8da803feb3d55ee739d7400ff098256b',
    userid: '4028cac3614cd2f901614cf8be1f0324',
    username: '',
    channel: 'webim',
    debug: true,
    type: 'message',
    contextid: '486b1e7469064f51a88e5f5e335f21ff',
    orgi: 'ukewo',
    message: searchText
  })

  sendWord.value = ''
}

onBeforeUnmount(() => {
  socket.destory()
})

const initData = {
  orgi: serverInfo.orgi,
  appid: '8da803feb3d55ee739d7400ff098256b',
  aiid: props.aiid,
  session: '2f068570bec246c4879dfedaa20a59fc',
  userid: userInfo.id,
  user: userInfo.id,
  debug: true,
}

console.log(initData)
// const chatSocketStore = useChatSocketStore()
// chatSocketStore.bindEvents({
//   orgi: serverInfo.orgi,
//   appid: '',
//   aiid: '',
//   session: '',
//   userid: userInfo.id,
//   user: userInfo.id,
//   debug: true,
// })



const handleKeyDown = event =>{
  if(!event.shiftKey && event.keyCode == 13){
    event.cancelBubble=true;
    event.preventDefault();
    event.stopPropagation();
    sendMessage();
  } 
}
const onCopy = async (word) => {
  try {
    await navigator.clipboard.writeText(word);
    proxy.$Message.success('已复制');
  }catch(err) {
    proxy.$Message.error(err);
  }
}
</script>
<style lang="scss" scoped>
.chatbot-wrapper {
  background-color: #fff;
  border-radius: 8px;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .title {
    font-size: 20px;
    font-weight: bold;
    padding: 10px 20px;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
  }
  .content {
    margin-top: 50px;
    width: 100%;
    height: calc(100% - 180px);
    overflow-y: auto;
    padding: 10px 20px;
    position: relative;
  }
}

.chat-item {
  width: 100%;
  display: flex;
  flex-direction: column;
  &.client {
    .chat-toolbar, .chat-content {
      justify-content: flex-end;
    }
    .chat-content {
      text-align: right;
      .word {
        background-color: #e1eaff;
        border-radius: 8px;
        border-top-right-radius: 0;
      }
    }
  }
  .chat-content  {
    display: flex;
    margin-top: 10px;
    justify-content: flex-start;
    text-align: left;
    margin-bottom: 10px;
    .word {
      padding: 10px;
      border-radius: 8px;
      border-top-left-radius: 0;
      background-color: #edeef1;
    }
  }
  .chat-toolbar {
    display: flex;
    align-items: center;
    .tools {
      display: flex;
      align-items: center;
      margin: 0 6px;
      .btn {
        border: 1px solid #DFE2EA;
        padding: 0 4px;
        cursor: pointer;
        &:first-of-type {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        &:last-of-type {
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
      }
    }
    .avatar {
      width: 28px;
      height: 28px;
      border-radius: 6px;
    }
  }
}

.footer {
  position: absolute;
  bottom: 70px;
  left: 50%;
  width: calc(100% - 120px);
  transform: translateX(-50%);
  margin: 10px auto;
  .enter {
    display: flex;
    /* align-items: center; */
    width: 100%;
    padding: 10px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 10px;
    /* textarea.ivu-input, textarea, .ivu-input {
      width: 100%;
      height: 40px;
      line-height: 40px;
      max-height: 50vh!important;
    } */
  }
}
.suggest-item {
  cursor: pointer;
  padding: 6px 0;
  color: #2d8cf0;
}
</style>